<?php
namespace App\Repos;

use App\Models\Order;
use App\Models\OrderProduct;
use App\Models\OrderProcess;
use App\Models\OrderPoint;
use App\Models\OrderPrepay;
use App\Models\CustomerService;
use App\Services\RedisService;
use EasyWeChat;
use function EasyWeChat\Kernel\Support\generate_sign;
use DB;
use App\Repos\CartRepo;


class OrderRepo
{
	public static function  getPages($where=[],$num=10,$orderBy='id',$orderWay='desc')
	{	   
		$query = Order::query();	
		
	  	$list = $query->where($where)
	  				->with('products')
	  				->orderBy($orderBy,$orderWay)
	  				->paginate($num); 
	  	return $list;     
	}

	public static function  pages($where=[],$num=10,$orderBy='id',$orderWay='desc')
	{	   
		$query = Order::query();
		
		
		$status = array_pull($where,'status');
		if($status==1) {
			$query->whereIn('status',['1','2','3','4','5']);
		}elseif($status==100) {
			$query->where('status','100');
		}
		
	  	$list = $query->where($where)
	  				->with('products','address')
	  				->orderBy($orderBy,$orderWay)
	  				->paginate($num); 
	  	return $list;     
	}

	public static function find($where)
	{		
		$order = Order::where($where)->with('products','address')->first();
		return $order;
	}

	/**
	 * 创建订单
	 */
	public static function create($data,$carts)
	{
		$rs['status']  = true;
		$total_money   = $data['total_money']*100;		

		DB::beginTransaction();
		try {
			

			$order    = Order::create($data);
			foreach ($carts as $cart) {
				$op = array_except($cart->toArray(),'user_id');
				$op['order_id'] = $order->id;
				
				OrderProduct::create($op);

				CartRepo::release(['id'=>$op['id']]);
			}
			
			
			

			DB::commit();

		} catch (\Exception $e) {
			$rs['status'] = false;
			$rs['msg']    = $e->getMessage();			
			DB::rollBack();
			return $rs;
		}

		return $rs;

		// $unifyData['openid']       = $openid;
		// $unifyData['total_money'] = $total_money;
		// $unifyData['code']         = $data['code'];
		// $unifyData['order_id']    = $order->id;
		// return self::wechatUnifyOrder($unifyData);
	}

	


	/**
	 * 确认订单
	 */
	public static function confirm($data)
	{
		$rs['status'] = false;
		$rs['msg']    = '操作失败';
		
		
		//先检查订单的状态防止误操作 订单状态在待付款1或者已付款2的才可以确认
		
		DB::beginTransaction();
		try{
			$order = Order::find($data['order_id']);
			if($order->status!=1) {
				$rs['msg'] = '订单状态错误';
				return $rs;
			}

			$order->pre_money = $data['pre_money']*100;
			$order->status = 2;
			$order->save();

			$preData['order_id']  = $order->id;
			$preData['pre_code']  = 'PRE-'.$order->code;
			$preData['pre_money'] = $order->pre_money;
			$preData['status'] = 1;
			OrderPrepay::create($preData);

			DB::commit();
		} catch(\Exception $e) {
			$rs['msg'] = $e->getMessage();
			DB::rollBack();
			return $rs;
		}
		$rs['status'] = true;
		$rs['msg'] = '操作成功';
		return $rs;
	}

	/**
	 * 配送订单需要上传订单商品图片
	 */
	public static function orderPic($data)
	{

		$rs['status'] = false;
		$order_status = 4;
		DB::beginTransaction();
		try{
			$order = Order::find($data['order_id']);
			if(empty($order->address_id)) {
				$rs['msg'] = '此订单是自取订单无需上传照片';
				return $rs;
			}
			//配送订单确认后才能上图
			// if($order->status!=3){
			// 	$rs['msg'] = '请先确认订单';
			// 	return $rs;
			// }

			$order->status = $order_status;
			$order->save();

			// 更新订单商品表			
			$picWhere['order_id']   = $data['order_id'];
			$picWhere['product_id'] = $data['product_id'];	
			$pic = $data['pic'];

			OrderProduct::where($picWhere)->update(['pic'=>$pic]);
			


			$process['order_id']     = $data['order_id'];
			$process['shop_user_id'] = $data['shop_user_id'];
			$process['order_status'] = $order_status;
			$process['remark']       = '卖家上传订单商品图片';
			$flag = OrderProcess::create($process);

			DB::commit();
		} catch(\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		if($flag) {
			$rs['status'] = true;
			return $rs;
		}
		return $rs;
	}

	/**
	 * 开始配送
	 */
	public static function dispatch($data)
	{
		$rs['status'] = false;
		$order_status = 5;
		DB::beginTransaction();
		try{
			$order = Order::find($data['order_id']);
			if(empty($order->address_id)) {
				$rs['msg'] = '此订单是自取订单无需配送';
				return $rs;
			}
			//配送订单确认后要上传图才能继续
			if($order->status!=4){
				$rs['msg'] = '请先上传订单商品图片';
				return $rs;
			}

			$order->status = $order_status;
			$order->save();
			$process['order_id']     = $data['order_id'];
			$process['shop_user_id'] = $data['shop_user_id'];
			$process['order_status'] = $order_status;
			$process['remark']       = '卖家已配送';
			$flag = OrderProcess::create($process);	
			DB::commit();
		} catch(\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		if($flag) {
			$rs['status'] = true;
			return $rs;
		}
		return $rs;
		

	}

	/**
	 * 支付预付款
	 */
	public static function prepay($data)
	{
		$rs['status'] = false;
		$order = OrderPrepay::where('order_id',$data['order_id'])->first();
		if(!$order) {			
			$rs['msg'] = '订单不存在';
			return $rs;
		}

		if($order->status !=1 ){
			$rs['msg'] = '订单状态错误'; 
			return $rs;
		}	

		$data['code']        = $order->pre_code;
		$data['total_money'] = $order->pre_money;
		$data['url']  = config('app.url').'/wechat/prepay-notify';
		$rs['status'] = true;
		$rs['data'] = self::wechatUnifyOrder($data);
		return $rs;

	}

	/**
	 * 支付尾款
	 */
	public static function pay($data)
	{
		$rs['status'] = false;
		$order = Order::where(['code'=>$data['code']])->first();
		if(!$order) {			
			$rs['msg'] = '订单不存在';
			return $rs;
		}

		if($order->status !=1 ){
			$rs['msg'] = '订单状态错误'; 
			return $rs;
		}	

		$data['total_money'] = $rs->total_money-$rs->pre_money;
		$rs['status'] = true;
		$rs['data'] = self::wechatUnifyOrder($data);
		return $rs;

	}

	public static function count($where)
	{
		$user_id   = $where['user_id'];
		$key       = $where['key'];
		$redis_key = 'fruit:users:order:count:'.$user_id.'_'.$key;
		$num = RedisService::get($redis_key);
		if($num) return $num;

		$num    = Order::where(['user_id'=>$user_id])
						->whereIn('status',$where['status'])
						->count();
		$redis_key = 'fruit:users:order:count:'.$user_id.'_'.$key;
		$redis_data = (int)$num;				
		RedisService::set($redis_key,$redis_data);
		return $num;
	}


	public static function cancle($data)
	{
		$rs['status'] = false;
		$where['code'] = $data['code'];	
		$order = Order::where($where)->first();
		if(!$order) {			
			$rs['msg'] = '订单不存在';
			return $rs;
		}
		// if($order->status !=1 ){
		// 	$rs['msg'] = '订单状态不允许取消'; 
		// 	return $rs;
		// }
		DB::beginTransaction();
		try {
			if($orer->status==1) {
				// 待确认订单不需要审核
				$order->status = '-1';	
			} else {
				// 其他状态需要 卖家审核
				$order->status = '-3';
			}
			
			$order->save();
			// 恢复优惠券
			if($order->user_coupon_id){
				UserCouponRepo::update(['id'=>$order->user_coupon_id],['is_used'=>0]);
			}
			
			DB::commit();
		} catch (\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		$rs['status'] = true;
		return $rs;	
	}

	
	public static function wechatUnifyOrder($data)
	{
		$notify_url = config('app.url').'/wechat/pay-notify';
		if($data['url']) {
			$notify_url = $data['url'];
		}
		$payment = EasyWeChat::payment(); // 微信支付
		$result = $payment->order->unify([
		    'body'         => '迎亲记',
		    'out_trade_no' => $data['code'],
		    'trade_type'   => 'JSAPI',  // 必须为JSAPI
		    'openid'       => $data['openid'], // 这里的openid为付款人的openid
		    'total_fee'    => $data['total_money'], // 总价单位分
		    'timeStamp'    => time(),
		    'notify_url'   => $notify_url
		]);
		
		// 如果成功生成统一下单的订单，那么进行二次签名
		if ($result['return_code'] === 'SUCCESS') {
		    // 二次签名的参数必须与下面相同
		    $params = [
		        'appId'     => config('wechat.mini_program.default.app_id'),
		        'timeStamp' => time(),
		        'nonceStr'  => $result['nonce_str'],
		        'package'   => 'prepay_id=' . $result['prepay_id'],
		        'signType'  => 'MD5',
		    ];
		    // config('wechat.payment.default.key')为商户的key
		    $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
		    $params['signJs'] = $result['sign'];
		    $params['order_id']      = $data['order_id'];
		    $params['order_code']    = $data['code'];
		    $params['order_created'] = date('Y-m-d H:i:s');
		    return $params;
		} else {
		    return $result;
		}
	}

	/**
	 * 商家扫码方式确认订单完成
	 * 有返现要发现
	 */
	public static function validPay($data)
	{
		$rs['status'] = false;
		$status = 100;
		$where['shop_id'] = $data['shop_id'];
		$where['id']    = $data['order_id'];
		DB::beginTransaction();
		try {
			$order = Order::where($where)->first();
			if($order->status>=100) {
				$rs['msg'] = '订单状态错误';
				return $rs;
			}

			if($order) {
				$order->completed_at = date('Y-m-d H:i:s');
				$order->status = $status;
				$order->save();
			}
			// 店铺是否返现
			$shop = ShopRepo::find(['id'=>$data['shop_id']]);

			if($shop->cashback_rate>0) {
				$products = OrderProduct::where(['order_id'=>$data['order_id']])
										  ->get();
										
				foreach ($products as $k => $v) {
					//产品是否返现
					if(object_get($v,'product.is_cashback')){
						$user_money['shop_id']    = $data['shop_id'];
						$user_money['order_id']   = $data['order_id'];
						$user_money['user_id']    = $order->user_id;
						$user_money['product_id'] = $v->product_id;
						$user_money['type']  = 1;
						$user_money['money'] = $v->total_price*($shop->cashback_rate/100);
						// 保存返现信息；
						UserMoneyLogRepo::create($user_money);
					}
				}	
			}	

			$process['order_id']     = $data['order_id'];
			$process['shop_user_id'] = $data['shop_user_id'];
			$process['order_status'] = $status;
			$process['remark']       = '订单完成';
			$flag = OrderProcess::create($process);
			$rs['status'] = true;
			DB::commit();
		} catch (\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
		}

		return $rs;	

	}


	


	public static function total($where)
	{
		$today =  Order::whereDate('created_at', '=', date('Y-m-d'))->sum('total_amount');
		$all = Order::sum('total_amount');
		$data['today'] = $today;
		$data['all'] = $all;
		return $data;
	}

	public static function reject($data)
	{
		$rs['status'] = false;
		$order_status = '-2';
		$where = array_only($data,['id','shop_id']);
		$order = Order::where($where)->first();

		if(empty($order)) {
			$rs['msg'] = '订单不存在';
			return $rs;
		}
		// 只有待确认状态的订单才能被拒单
		if($order->status!=1) {
			$rs['msg'] = '订单当前状态无法拒绝';
			return $rs;
		}

		$order->status = $order_status;
		$flag = $order->save();
		if($flag) {
			$rs['status'] = true;

			$process['order_id']     = $data['id'];
			$process['shop_user_id'] = $data['shop_user_id'];
			$process['order_status'] = $order_status;
			$process['remark']       = '卖家拒绝接单';
			$flag = OrderProcess::create($process);	
			return $rs;
		}
		$rs['msg'] = '拒单失败';
		return $rs;
	}

	/**
	 * 同意 用户提出 取消的订单申请
	 */
	public static function approval($data)
	{
		$rs['status'] = false;
		$order_status = $data['status'];
		$where = array_only($data,['id','shop_id']);
		$order = Order::where($where)->first();

		if(empty($order)) {
			$rs['msg'] = '订单不存在';
			return $rs;
		}
		// 只有待确认状态的订单才能被拒单
		if($order->status!=-3) {
			$rs['msg'] = '订单状态错误';
			return $rs;
		}

		$order->status = $order_status;
		$msg = $order_status==90?'卖家同意取消订单':'卖家拒绝取消订单';
		$flag = $order->save();
		if($flag) {
			$rs['status'] = true;

			$process['order_id']     = $data['id'];
			$process['shop_user_id'] = $data['shop_user_id'];
			$process['order_status'] = $order_status;
			$process['remark']       = $msg;
			$flag = OrderProcess::create($process);	
			return $rs;
		}
		$rs['msg'] = '操作失败';
		return $rs;
	}

	



	public static function point($data)
	{
		$rs['status'] = false;
		$rs['msg'] = '评价失败';
		$where['code']    = array_pull($data,'code');
		$where['user_id'] = $data['user_id'];
		DB::beginTransaction();
		try {
			$order = Order::where($where)->first();
			if(!$order) {
				$rs['msg'] = '订单不存在';
				return $rs;
			}

			if($order->status!=100) {
				$rs['msg'] = '付款后才能评价订单';
			}
			$order->status = 200;
			$order->save();


			
			foreach($data['product_id'] as $k=>$p) {
				$op['order_id']   = $order->id;
				$op['user_id'] 	  = $data['user_id'];
				$op['product_id'] = $p;
				$op['point']      = $data['point'][$k];
				$flag = OrderPoint::create($op);
			}
			
			if($flag) {
				DB::commit();
				$rs['status'] = true;
				return $rs;
			}
			DB::rollBack();
			return $rs;
			
		} catch (\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		return $rs;
	} 

	public static function orderCount()
	{
		$num = Order::count();
		return $num;
	}

	public static function orderAmount()
	{
		$total = Order::sum('total_money');
		return $total;	
	}

	public static function saveCustomerService($where)
	{
		$rs['status'] = false;
		$order = Order::where($where)->first();
		if($order) {
			$data = $order->toArray();
			$cs = array_only($data,['user_id','shop_id']);
			$cs['order_id'] = $data['id'];
			$flag = CustomerService::create($cs);
			if($flag){
				$order->status = '-9';
				$order->save();
				$rs['status']  = true;
				return $rs;	
			} 
		} else {
			$rs['msg'] = '订单不存在';
		}
		return $rs;
	}



	

	

	
	
	

	
	
	
}